import { loginApi } from '@/api/user'
import router from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken()
  }
}

const state = getDefaultState()

const mutations = {
  // 存token
  SET_TOKEN(state, token) {
    // 1.1 往本地存
    setToken(token)
    // 1.2 往state中存
    state.token = token
  },
  // 删除token
  REMOVE_TOKEN(state) {
    removeToken()
    state.token = null
  }
}

const actions = {
  // user login
  async login(context, userInfo) {
    const { username, password } = userInfo
    const res = await loginApi({ username, password })

    context.commit('SET_TOKEN', res.token)
    Message.success('登录成功')
    router.replace('/')
  },
  logout(context) {
    context.commit('REMOVE_TOKEN')
    router.replace('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
